﻿using MediatR;
using Medical.Api.Read.Application.Command.RecyclingCleaning;
using Medical.Api.Read.Dto.RecyclingCleaning;
using Medical.Domain.DepartmentInfo;
using Medical.Domain.Enum;
using Medical.Domain.RecoveryCleaning;
using Medical.ErrorCode;
using Medical.Interstructrue.Base;
using Microsoft.EntityFrameworkCore;

namespace Medical.Api.Read.Application.Handler.RecyclingCleaning
{
    /// <summary>
    /// 获取已回收物品信息的命令处理
    /// </summary>
    public class GetRecoveredListCommandHandlter : IRequestHandler<GetRecoveredListCommand, ApiResult<List<RecoveredFinshDto>>>
    {

        /// <summary>
        /// 物品仓储
        /// </summary>
        private readonly IBaseRepository<ItemTable> itemTables;
        /// <summary>
        /// 回收登记仓储
        /// </summary>
        private readonly IBaseRepository<InstrumentRecovery> instrumentRecoveriesRep;
        /// <summary>
        /// 回收申请仓储
        /// </summary>
        private readonly IBaseRepository<RecyclingTable> recyclingTablesRep;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="itemTables">物品仓储</param>
        /// <param name="InstrumentRecoveriesRep">回收登记仓储</param>
        /// <param name="recyclingTablesRep">回收申请仓储</param>
        public GetRecoveredListCommandHandlter(IBaseRepository<ItemTable> itemTables, IBaseRepository<InstrumentRecovery> InstrumentRecoveriesRep, IBaseRepository<RecyclingTable> recyclingTablesRep)
        {
            this.itemTables = itemTables;
            instrumentRecoveriesRep = InstrumentRecoveriesRep;
            this.recyclingTablesRep = recyclingTablesRep;
        }

        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns></returns>
        public async Task<ApiResult<List<RecoveredFinshDto>>> Handle(GetRecoveredListCommand request, CancellationToken cancellationToken)
        {

            try
            {
                // 获取所有不是待回收的器械记录，明确指定要查询的列
                var recoveryItems = await instrumentRecoveriesRep.GetAll()
                    .Where(r => r.Status == RecoveryStatusEnum.已回收)
                    .Select(r => new
                    {
                        r.Id,
                        r.RecoveredBy,
                        r.RecoveryTime,
                        r.Status,
                        r.EquipmentPackageId
                    })
                    .ToListAsync(cancellationToken);

                // 获取物品表，明确指定要查询的列
                var itemList = await itemTables.GetAll()
                    .Where(i => !i.IsDeleted)
                    .Select(i => new
                    {
                        i.Id,
                        i.ItemCode,
                        i.ItemName,
                        i.RecyclingId,
                        i.ItemNumber,
                        i.ItemType,
                        i.Itemattribute,

                    })
                    .ToListAsync(cancellationToken);

                // 获取回收申请表，明确指定要查询的列
                var recyclingList = await recyclingTablesRep.GetAll()
                    .Where(r => !r.IsDeleted)
                    .Select(r => new
                    {
                        r.Id,
                        r.Urgent,
                        r.ReceptionUnit
                    })
                    .ToListAsync(cancellationToken);

                // 构建结果列表
                var result = new List<RecoveredFinshDto>();

                foreach (var recovery in recoveryItems)
                {
                    // 检查器械包ID列表是否包含物品表中的ID
                    if (recovery.EquipmentPackageId != null && recovery.EquipmentPackageId.Count > 0)
                    {
                        foreach (var packageId in recovery.EquipmentPackageId)
                        {
                            var item = itemList.FirstOrDefault(i => i.Id == packageId);
                            if (item != null)
                            {
                                var recycling = recyclingList.FirstOrDefault(r => r.Id == item.RecyclingId);
                                if (recycling != null)
                                {
                                    result.Add(new RecoveredFinshDto
                                    {
                                        Id = recovery.Id,
                                        ItemCode = item.ItemCode,
                                        ItemName = item.ItemName,
                                        Itemattribute = item.Itemattribute,
                                        ItemType = item.ItemType.ToString(),
                                        ApplyDepartment = recycling.ReceptionUnit.ToString(),
                                        Quantity = item.ItemNumber,
                                        Urgent = recycling.Urgent,
                                        RecoveredBy = recovery.RecoveredBy ?? string.Empty,
                                        RecoveryTime = recovery.RecoveryTime,
                                        Status = recovery.Status.ToString(),
                                    });

                                }
                            }
                        }
                    }
                }

                return new ApiResult<List<RecoveredFinshDto>>
                {
                    Code = ApiEnums.Success,
                    Data = result,
                    Msg = "获取成功"
                };
            }
            catch (Exception ex)
            {
                return new ApiResult<List<RecoveredFinshDto>>
                {
                    Code = ApiEnums.Error,
                    Msg = ex.Message,
                    Data = null
                };
            }
        }

    }

}
